<template>
  <div class="search">
    <section>
      <div class="search-history">
        <h2>
          <i class="iconfont icon-fangdajing"></i>
          <span>历史搜索</span>
          <span @click="clearSearchHistory">清空</span>
        </h2>
        <ul v-if="searchArr?.length">
          <li v-for="(item, index) in searchArr" :key="index">
            <span @click="goSearchByHistory(item)">{{ item }}</span>
          </li>
        </ul>
        <div v-else>暂无历史搜索</div>
      </div>
    </section>
    <section class="search-history">
      <h2>热门推荐</h2>
    </section>
  </div>
</template>

<script setup>
import { ref, defineComponent, onMounted } from 'vue'
import { showConfirmDialog } from 'vant'
import { useRouter } from 'vue-router'
import { emitter } from '@/common/utils/EventMitt'
const searchIndex = defineComponent({
  name: 'SearchIndex',
  // 组件的其他选项...
})
let searchArr = ref([])
onMounted(() => {
  searchArr.value = JSON.parse(localStorage.getItem('searchList')) || []
})

const clearSearchHistory = () => {
  showConfirmDialog({
    title: '清空历史搜索',
    message: '确定要清空历史搜索记录吗？',
  })
    .then(() => {
      // on confirm
      localStorage.removeItem('searchList')
      searchArr.value = []
    })
    .catch(() => {
      // on cancel
      console.log('取消清空历史搜索')
    })
}

const router = useRouter()
const goSearchByHistory = (label) => {
  if (!label) return
  emitter.emit('updata:Keyword', label)
  router.push({ name: 'SearchList', query: { keyword: label } })
}

const deleteLabel = (label) => {
  if (!label) return

  const searchList = JSON.parse(localStorage.getItem('searchList')) || []

  let index = searchList.indexOf(label)
  if (index > -1) {
    showConfirmDialog({
      title: '删除搜索记录',
      message: '确定要删除[' + label + ']历史搜索记录吗？',
    })
      .then(() => {
        // on confirm
        searchList.splice(index, 1)
        searchArr.value = searchList
        localStorage.setItem('searchList', JSON.stringify(searchList))
      })
      .catch(() => {
        // on cancel
        console.log('取消清空历史搜索')
      })
  }
}
</script>

<style>
.search {
  display: flex;
  flex-direction: column;
  width: 100vw;
  height: auto;
  overflow: hidden;
  background-color: #fff;
}

section {
  flex: 1;
  background-color: #fff;
  overflow: hidden;
}

.search-history h2 {
  position: relative;
  padding: 0.533333rem;
  font-weight: 400;
  font-size: 0.48rem;
}

.search-history h2 i {
  padding-right: 0.08rem;
  color: #999;
  font-size: 0.48rem;
}

.search-history h2 span:last-child {
  position: absolute;
  right: 0.533333rem;
}

.search-history ul {
  display: flex;
  flex-wrap: wrap;
  padding: 0 0.266666rem;
}

.search-history ul li {
  margin: 0.266666rem;
  padding: 0.08rem 0.16rem;
  font-size: 0.373333rem;
  border: 1px solid #ccc;
}
</style>
